package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 订单业务层
 * @author Xiao
 * @date 2021/9/28
 */
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    /**
     * 分页查询订单
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @Override
    public Page<Orders> getOrderDetailPage(Integer page, Integer pageSize, String number, String beginTime, String endTime) {
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(number), Orders::getNumber, number);
        wrapper.ge(StringUtils.isNotEmpty(beginTime), Orders::getOrderTime, beginTime);
        wrapper.le(StringUtils.isNotEmpty(endTime), Orders::getOrderTime, endTime);
        wrapper.orderByAsc(Orders::getOrderTime);
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        return this.page(ordersPage, wrapper);
    }
    /**
     * 修改订单状态
     * @param orders
     * @return
     */
    @Override
    public boolean editOrderDetail(Orders orders) {
        return this.updateById(orders);
    }
    /**
     * 提交订单
     * @param orders
     * @return
     */
    @Override
    @Transactional
    public void addOrderApi(Orders orders) {
        //设置id、订单号、状态、userId、下单时间、支付时间
        //IDWorker：ID获取工具类
        orders.setId(IdWorker.getId());
        orders.setNumber(String.valueOf(orders.getId()));
        orders.setStatus(2);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        //计算并设置订单金额
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);
        if(shoppingCarts == null || shoppingCarts.size() == 0){
            throw new CustomException("购物车为空，不能下单");
        }
        AtomicInteger amount = new AtomicInteger();
        List<OrderDetail> orderDetails = shoppingCarts.stream().map(item -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(item, orderDetail);
            orderDetail.setOrderId(orders.getId());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        orders.setAmount(new BigDecimal(amount.get()));
        //设置下单用户的用户名
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getId, BaseContext.getCurrentId());
        User user = userService.getOne(userWrapper);
        orders.setUserName(user.getName());
        //设置收货人信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        orders.setPhone(addressBook.getPhone());
        //orders.setAddress(addressBook.getDetail());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        orders.setConsignee(addressBook.getConsignee());
        //存储到订单表
        this.save(orders);
        //存储订单详情，清空购物车
        orderDetailService.addOrderDetail(orderDetails);
        shoppingCartService.clearCartApi();
    }

    /**
     * 分页查询订单
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page<OrdersDto> orderPagingApi(Integer page, Integer pageSize) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        wrapper.orderByDesc(Orders::getOrderTime);
        this.page(ordersPage, wrapper);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");
        List<Orders> orders = ordersPage.getRecords();
        List<OrdersDto> ordersDtos = orders.stream().map(item -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            List<OrderDetail> orderDetails = orderDetailService.getByOrderId(item.getId());
            ordersDto.setOrderDetails(orderDetails);
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(ordersDtos);
        return ordersDtoPage;
    }

    /**
     * 再来一单
     * @param orders
     * @return
     */
    @Override
    public boolean orderAgainApi(Orders orders) {
        List<OrderDetail> orderDetails = orderDetailService.getByOrderId(orders.getId());
        List<ShoppingCart> shoppingCarts = orderDetails.stream().map(item -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(item, shoppingCart, "id");
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            return shoppingCart;
        }).collect(Collectors.toList());
        return shoppingCartService.orderAgainApi(shoppingCarts);
    }
}
